#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
'''
Created on May 27, 2013

@author: join
'''
import os
from django.db import transaction

from rest_framework.response import Response

from cvirt.manager.models import Template
from cvirt.manager.serializers import TemplateSerializer
from cvirt.manager.views import NamedAPIViewMixIn, BaseRetriveAPIView
from cvirt.tasks import delete_template


class TemplateInfo(NamedAPIViewMixIn, BaseRetriveAPIView):
    model = Template
    serializer_class = TemplateSerializer

    def _get(self, request, *args, **kwargs):

        os_type = request.GET.get("os_type");
        dataset = None

        if os_type:
            dataset = Template.objects.filter(os_type=os_type)
        else:
            dataset = Template.objects.all()

        result = self.paginate(request, dataset, TemplateSerializer)
        return Response(result)

    @transaction.autocommit
    def delete_all(self, request, *args, **kwargs):
        ids = request.DATA.get('ids')
        for id in ids:
            template = Template.objects.get_or_none(id=id)
            if template:
                delete_template.call_in_cluster(template.storage.cluster.id,os.path.join(template.storage.mount_point,"images",template.name))
                template.remove()
        return Response(200)

    @transaction.autocommit
    def delete(self, request, *args, **kwargs):

        _id = kwargs.get('pk')

        template = Template.objects.get_or_none(id = _id)
        if template:
            delete_template.call_in_cluster(template.storage.cluster.id,os.path.join(template.storage.mount_point,"images",template.name))
            template.remove()
        return Response(200)